using System;
using System.Collections.Generic;
using System.Linq;
using data.contracts;
using HtmlAgilityPack;
using Twitterizer;

namespace twittersearch
{
    public class Mapper
    {
        public event Action<IEnumerable<Tweet>>  Out_Result;

        public void In_Map(TwitterSearchResultCollection twitterSearchResultCollection) {   
            Out_Result(twitterSearchResultCollection.Select(CreateTweet));
        }

        private static Tweet CreateTweet(TwitterSearchResult result) {
            return new Tweet {
                ImageSource = result.ProfileImageLocation,
                Name = string.Format("@{0}, {1:dd.MMM HH:mm} via {2}",
                    result.FromUserScreenName, result.CreatedDate, ExtractApplicationName(result.Source)),
                Text = HtmlEntity.DeEntitize(result.Text)
            };
        }

        private static string ExtractApplicationName(string sourceAsHtml) {
            var html = HtmlEntity.DeEntitize(sourceAsHtml);
            var node = HtmlNode.CreateNode(html);
            return node.InnerText;
        }
    }
}